package com.qian.ddj.bill.alipay;

import com.qian.api.ddj.model.Business;
import com.qian.api.ddj.service.*;
import com.qian.api.ddj.util.YunbaUtils;
import com.yaowk.api.system.service.IMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;

@Component
@Slf4j
public class StartListener implements CommandLineRunner {

    @Autowired
    private IBusinessService businessService;
    @Autowired
    private IPhoneCheckCodeService phoneCheckCodeService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private ISpiderService spiderService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private ILoginCodeService loginCodeService;
    @Autowired
    private YunbaUtils yunbaUtils;

    @Override
    public void run(String... strings) throws Exception {

        log.info(" ali spider begin");

        final ExecutorService executorService = Bill.executorService;

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                Set<Integer> runningSet = new HashSet<>();

                // 每10分钟查询一次是否有新账号
                while (true) {
                    List<Business> businesses = businessService.findByZFB();
                    for (Business business : businesses) {
                        if (!runningSet.contains(business.getId())) {
                            runningSet.add(business.getId());

                            Bill bill = new Bill();
                            bill.setAccount(business.getAccount());
                            bill.setBusinessId(business.getId());
                            bill.setPassword(business.getSecretKey());
                            bill.setPhoneCheckCodeService(phoneCheckCodeService);
                            bill.setMenuService(menuService);
                            bill.setOrderService(orderService);
                            bill.setSpiderService(spiderService);
                            bill.setBusinessService(businessService);
                            bill.setYunbaUtils(yunbaUtils);
                            executorService.execute(bill);

                            log.info("execute " + business.getName());
                        }
                    }

                    try {
                        Thread.sleep(600000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
